<?php

namespace App\Http\Controllers\Admin;

use App\Models\AdminUser;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class LoginController extends BaseController
{
    public function __construct()
    {
        //$this->middleware('check_admin_login');
    }

    /**
     * 后台登录
     * @param Request $request
     * @return array
     */
    public function login(Request $request)
    {
        $username = trim($request->get('username'));
        $password = trim($request->get('password'));

        if(empty($username) || empty($password))
        {
            return $this->err(1,200,'','参数错误');
        }

        $adminuser = AdminUser::query()->select(['id','username','password'])->where('username',$username)->first();
        if(empty($adminuser))
        {
            return $this->err(1,200,'','账号或者密码错误');
        }

        if (Hash::check($password, $adminuser->password))
        {
            //账号密码正确
            //session(['book_shop_admin_info' => ['username' => $adminuser->username, 'admin_id' => $adminuser->id]]);
            $token = encrypt(json_encode(['username' => $adminuser->username, 'admin_id' => $adminuser->id]));
            AdminUser::where('id',$adminuser->id)->update([
                'last_login_at' => Carbon::now()
            ]);
            return $this->ok(['access_token' => $token],'登录成功');
        }

        return $this->err(1,200,'','账号或者密码错误');
    }


    public function test(Request $request)
    {
        //$token = $request->header('token');
        //echo $adminuser = decrypt($token);die;
        echo 1;die;
        AdminUser::query()->insert([
            'username'   => 'admin',
            'password'   => Hash::make('adminuser'),
            'created_at' => Carbon::now(),
            'state'      => 1,
        ]);
    }
}
